<?php

namespace app\api\service;

use think\admin\Service;
use think\facade\Db;

/**
 * 会员数据接口服务
 * Class UserService
 * @package app\api\service
 */
class UserService extends Service
{
    /**
     * 会员余额日志
     * member_capital_flow
     * pay_type 1：收入，2：支出
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function capitalFlow($vipcode,$out_trade_no,$phone,$amount,$desc,$pay_type=2)
    {
        $mobile = self::GetVipDis('',$vipcode);
        //var_dump($mobile);
        $mobile = $mobile->Data[0]->Mobile?:'888'; //$mobile['Data'][0]['Mobile'];

        $balance_after = 0; // 变动后余额
        if($pay_type == 2){
            $amount = '-'.$amount;
        }
        $row = Db::connect('zs')->table('meal')->where(['mobile' => $mobile, 'is_deleted' => 0])->find();
        if($row){
            $balance_after = $row['balance'];
        }else{
            $rs = Db::connect('zs')->table('member_meal')->where(['vipcode' => $vipcode, 'is_deleted' => 0])->find();
            if($rs){
                $balance_after = $rs['balance'];
            }
        }
        $array=[
            "vipcode" => $vipcode,
            "phone" => $phone,
            "amount" => $amount,
            "pay_type" => $pay_type,
            "out_trade_no" => $out_trade_no,
            "desc" => $desc,
            "balance_after" => $balance_after,
            "balance_before" => $balance_after-$amount,   // 变动前余额
        ];
        Db::connect('zs')->table("member_capital_flow")->insert($array);
    }
    /**
     * 获取科传会员资料
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function GetVipDis($phone=null,$vipcode=null)
    {
        $arr = [
            'method' => 'GetVipDis',
            'user' => 'TC',
            'crc' => '1505977404043',
            'sign' => 'e5532c2c6641367dfce34d025e51b784',
            "data" => [
                'MallId' => '000001',
                'CardNo' => null,
                'VipCode' => $vipcode,
                'SurName' => null,
                'Mobile' => $phone,
                'VipId' => null,
                'IsThisCircle' => false
            ]
        ];

        $data = json_encode((object)$arr);
        $post_meta = self::crm_post_https($data);
        $post_coupon = json_decode($post_meta);
        //$coupon = $post_coupon->Data;
        //var_dump($post_coupon);
        return $post_coupon;
    }
    /**
     * 更新电子券领取状态，科传券
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function updateKcTicket($vipcode,$ticketid,$n_no)
    {
        //更新销售日志
        Db::connect('zs')->table("member_coupon_provide")
            ->where('tid', $ticketid)
            ->where('uid', $vipcode)
            ->update(['status' => 2, 'docno' => $n_no]); //核销科传电子券
    }
    /**
     * 写入电子券日志
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function updateSaleLog($n_no,$ticketid,$ticket_amount,$Amount)
    {
        //更新销售日志
        Db::connect('zs')->table("meal_details_store_log")
            ->where('n_no', $n_no)
            ->inc('ticket_amount', $ticket_amount?:0)
            ->inc('integral', $Amount?:0)
            ->update(['ticketid' => $ticketid]);
    }
    /**
     * 写入电子券日志
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function ticketCancelLog($vipcode,$order_on,$ticketid,$tid,$bid,$amount,$n_no)
    {
        $array=[
            'n_no'=> $n_no,
            "amount" => $amount,
            'order_on'=> $order_on,
            'businessid'=> $bid,
            'status'=> 1,
            'ticketid'=> $ticketid,
            'tid'=> $tid,
            'vipcode'=> $vipcode
        ];
        Db::connect('zs')->table("member_ticket_log")->insert($array);
    }
    /**
     * 写入积分抵扣日志
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function payBonusLog($vipcode,$order_on,$bonus,$CurrentBonus,$n_no=null,$amount=0,$bid=0)
    {
        $array=[
            'vipcode'=>$vipcode,
            "businessid" => $bid,
            'order_on'=> $order_on,
            'CurrentBonus'=> $CurrentBonus,
            'bonus'=> $bonus,
            'n_no'=> $n_no,
            'amount' => $amount
        ];
        Db::connect('zs')->table("member_paybonus_log")->insert($array);
    }
    /**
     * 余额扣减接口
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function epay($vipcode,$phone,$amount, $desc = '停车缴费')
    {
        $meal = Db::connect('zs')->table('meal')->where(['mobile' => $phone, 'is_deleted' => 0])->find();
        //var_dump($meal);
        if($meal){
            //有员工数据
            if($meal['balance']>=$amount){
                Db::connect('zs')->table('meal')->where('mobile', $phone)->where('is_deleted', 0)->dec('balance', $amount)->update();

                self::capitalFlow($vipcode,'',$phone,$amount,$desc,2); //记录资金日志
                return 0;
            }else{
                return 1;
            }

        }else{
            $user = Db::connect('zs')->table('member_meal')->where(['loginid' => $vipcode])->find();
            if($user['balance']>=$amount){
                Db::connect('zs')->table('member_meal')->where('loginid', $vipcode)->dec('balance', $amount)->update();

                self::capitalFlow($vipcode,'',$phone,$amount,$desc,2); //记录资金日志
                return 0;
            }else{
                return 1;
            }
        }
    }
    public static function queryMeal($mobile)
    {
        $meal = Db::connect('zs')->table('meal')->where(['mobile' => $mobile])->find();
        return $meal;
    }
    /**
     * 余额增加接口
     */
    public static function epayAdd($vipcode,$phone,$amount, $desc = '活动奖励', $out_trade_no = '')
    {
        $meal = Db::connect('zs')->table('meal')->where(['mobile' => $phone, 'is_deleted' => 0])->find();
        //var_dump($meal);
        if($meal){
            //有员工数据
                Db::connect('zs')->table('meal')->where('mobile', $phone)->where('is_deleted', 0)->inc('balance', $amount)->update();

                self::capitalFlow($vipcode,$out_trade_no,$phone,$amount,$desc,1); //记录资金日志
                return 0;

        }else{
            $user = Db::connect('zs')->table('member_meal')->where(['loginid' => $vipcode])->find();
                Db::connect('zs')->table('member_meal')->where('loginid', $vipcode)->inc('balance', $amount)->update();

                self::capitalFlow($vipcode,$out_trade_no,$phone,$amount,$desc,1); //记录资金日志
                return 0;
        }
    }
    /**
     * 插入充值记录表
     */
    public static function insertRecharge($amount, $vipcode, $mobile, $out_trade_no = '')
    {
        $meal = self::queryMeal($mobile);
        //插入充值记录
        $recharge=array();
        $recharge['amount'] = $amount;
        $recharge['vipcode'] = $vipcode;
        $recharge['mobile'] = $mobile;
        $recharge['a_class'] = 3; // 3:活动充值
        $recharge['out_trade_no'] = $out_trade_no;
        // 我的>>会员充值>>资金记录的接口（api/user/getCapitalFlow）会用到lastname
        $recharge['lastname'] = $meal['id'] ?? null;
        Db::connect('zs')->table('meal_recharge_record')->insert($recharge);
    }
    /**
     * 核销停车券
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function tkPay($tkcode,$carNumber)
    {
        $time = date("Y-m-d H:i:s",time());

/*        $tkUser = Db::name('car_tk_c')->where('tkcode', $tkcode)->find(); //查询券属于哪个商户

        $tkInfo = Db::name('car_tk')->where('tkid', $tkUser['tkid'])->find(); //查询券抵扣时间

        Db::name('car_tk_b')
            ->where('bid', $tkUser['bid'])
            ->dec('freeTime', $tkInfo['freeTime'])
            ->update(); //更新商户库存*/

        $tk = Db::name('car_tk_c')->where('tkcode', $tkcode)->update(['status' => 0,"gtime" => $time,"carNumber" => $carNumber]); //核销券

        if($tk === false){
            return 1;
        }else{
            return 0;
        }
    }
    /*
     * 科传电子券领取日志
    * @return array
    * @throws \think\Exception
    * @throws \think\db\exception\DataNotFoundException
    * @throws \think\db\exception\DbException
    * @throws \think\db\exception\ModelNotFoundException
    */
    public static function ticketLog($vipcode,$ticketid,$errcode,$errmsg)
    {
        $data['vipcode'] = $vipcode;
        $data['ticketid'] = $ticketid;
        $data['status'] = $errcode;
        $data['errmsg'] = $errmsg;
        $logId = Db::connect('zs')->table('member_goticket_log')->insertGetId($data);
        return $logId;
    }
    /*
    * 接口日志
    * @return array
    * @throws \think\Exception
    * @throws \think\db\exception\DataNotFoundException
    * @throws \think\db\exception\DbException
    * @throws \think\db\exception\ModelNotFoundException
    */
    public static function carLog($url,$arr,$post_meta)
    {
        //写入日志
        $data = ['apiName' => $url,'post' => $arr, 'content' => $post_meta];
        Db::name('car_log')->insert($data);

        return;
    }
    /*
    * 会员进行积分抵现
    * @return array
    * @throws \think\Exception
    * @throws \think\db\exception\DataNotFoundException
    * @throws \think\db\exception\DbException
    * @throws \think\db\exception\ModelNotFoundException
     */
    public static function PayBonusWorth($vipcode, $Amount, $StoreId, $DocNo, $BoNo)
    {
        $tx = date('YmdHis');
        //$tdate = date('Ymd');
        $data = [
            "reqdate" => "20190312",
            "reqtime" => "142158",
            'method' => 'PayBonusWorth_WebService',
            'user' => 'TC',
            'crc' => '1552371718902',
            'sign' => 'ef15623fecdb3b493cf3554a8093921a',
            "data" => [
                "vip" => [
                    "VipCode" => $vipcode,
                    "TxDateTime" => $tx,
                    "MallId" => "000001",
                    "StoreId" => $StoreId, //店铺号
                    "TillId" => "00",
                    "User" => "YKT",
                    "SalesMan" => "YKT",
                    "TenderList" => [
                        [
                            "TenderId" => "JF", //付款方式ID（积分抵现）（如为退积分抵现就可以不传）
                            "TenderAmount" => $Amount, //付款金额（需要抵现的金额）（退积分抵现的时候为负数）（如为退积分抵现就可以不传）
                            "IsBonusWorth" => "1" //是否是本次的积分抵现（0：否 1：是）（如为退积分抵现
                        ]
                    ],
                    "ItemList" => null,
                    "Remark" => null,
                    "BarCode" => null,
                    "Parent_DocNo" => null,
                    "Bonus_DocNo" => $BoNo
                ],
                "vipPwd" => "",
            ]
        ];
        $data2 = json_encode((object)$data);
        $post_meta = self::crm_post_https($data2);
        $post_link = json_decode($post_meta, true);

        return $post_link;
    }
    /*
    * 科传电子券核销
    * @return array
    * @throws \think\Exception
    * @throws \think\db\exception\DataNotFoundException
    * @throws \think\db\exception\DbException
    * @throws \think\db\exception\ModelNotFoundException
     */
    public static function TicketPay($vipcode, $SerialId, $StoreId, $DocNo, $TotalAmount)
    {
        $tx = date('YmdHis');
        //$tdate = date('Ymd');
        $data = [
            'method' => 'TicketPay',
            'user' => 'TC',
            'crc' => '15059774000004043',
            'sign' => 'e5532c2c6641367dfce34d025e51b78432',
            "data" => [
                "VipCode" => $vipcode,
                "SerialId" => $SerialId, //兑换码
                "RedemptionAmount" => 0.01, //本次兑换的金额(如无需验证，则传0.01)
                "SalesData_Ticket" => [
                    "TxDateTime" => $tx, //销售时间yyyyMMddhhmmss
                    "MallId" => "000001",
                    "StoreId" => $StoreId, //店铺号
                    "TillId" => "00",
                    "DocNo" => $DocNo, //销售流水号
                    "User" => "YKT",
                    "Remark" => null,
                    "ItemList" => null,
                    "TenderList" => null,
                    "TotalAmount" => $TotalAmount //销售总金额
                ],
                "CRC" => "$tx,$StoreId,00,$SerialId"
                //"CRC"=>"20170905144601,S001,00,57641276888663446975" //销售日期yyyyMMddhhmmss+,+店铺号+,+收银机号+,+兑换码
            ]
        ];
        $data2 = json_encode((object)$data);
        $post_meta = self::crm_post_https($data2);
        $post_link = json_decode($post_meta);
        //var_dump($data2);
        return $post_link;
    }
    /*
    * 获取会员的积分抵现比例
    * @return array
    * @throws \think\Exception
    * @throws \think\db\exception\DataNotFoundException
    * @throws \think\db\exception\DbException
    * @throws \think\db\exception\ModelNotFoundException
    */
    public static function BonusWorthQuery($vipcode, $StoreId)
    {
        $data = [
            'method' => 'BonusWorth_Query_WebService',
            'user' => 'TC',
            'crc' => '1505872460746',
            'sign' => '3bb48eb39a7fcab43d147531b06616d0',
            "data" => [
                "VipCode" => $vipcode,
                "StoreId" => $StoreId,
                "MallId" => "000001"
            ]
        ];
        $data2 = json_encode((object)$data);
        $post_meta = self::crm_post_https($data2);
        $post_link = json_decode($post_meta, true);
        //$coupon = $post_link->Data;
        return $post_link;
    }
    /*
    * 查询积分抵扣流水号
    * @return array
    * @throws \think\Exception
    * @throws \think\db\exception\DataNotFoundException
    * @throws \think\db\exception\DbException
    * @throws \think\db\exception\ModelNotFoundException
    */
    public static function GetBonusWorthDocNo()
    {
        $data = [
            'method' => 'GetBonusWorthDocNo_WebService',
            'user' => 'TC',
            'crc' => '1505872460746',
            'sign' => '3bb48eb39a7fcab43d147531b06616d0',
            'data' => ''
        ];
        $data2 = json_encode((object)$data);
        $post_meta = self::crm_post_https($data2);
        $post_link = json_decode($post_meta);
        $coupon = $post_link->Data;
        return $coupon;
    }
    /*
    * 科传电子券状态查询
    * @return array
    * @throws \think\Exception
    * @throws \think\db\exception\DataNotFoundException
    * @throws \think\db\exception\DbException
    * @throws \think\db\exception\ModelNotFoundException
    */
    public static function SelectTicketInfo($ticketid)
    {
        $data0=[
            'method'=> 'SelectTicketInfo',
            'user'=> 'TC',
            'crc'=> '1505977404043',
            'sign'=> 'e5532c2c6641367dfce34d025e51b784',
            "data"=> [
                'SerialId'=> $ticketid
            ]
        ];
        $data2= json_encode((object)$data0);
        $post_meta = self::crm_post_https($data2);
        $post_coupon = json_decode($post_meta);
        $coupon=$post_coupon->Data;

        return $post_coupon;
    }
    /*
    * 科传电子券领取
    * @return array
    * @throws \think\Exception
    * @throws \think\db\exception\DataNotFoundException
    * @throws \think\db\exception\DbException
    * @throws \think\db\exception\ModelNotFoundException
    */
    public static function vipGetTicket($vipcode,$TicketId)
    {
        $data=[
            'method'=> 'VipGetTicket',
            'user'=> 'TC',
            'crc'=> '1505977404043',
            'sign'=> 'e5532c2c6641367dfce34d025e51b784',
            'data'=> [
                'VipCode'=>$vipcode,
                'MallId'=>'000001',
                'MACAddress'=>'01-01-6C-06-A6-30',
                'TicketId'=>$TicketId,
                'Action'=>"T", //操作原因 B:满赠
                'User'=>'YKT'
            ]
        ];
        $data2= json_encode((object)$data);
        $post_meta = self::crm_post_https($data2);
        $post_link = json_decode($post_meta);

        return $post_link;
    }
    /*
    * 科传积分查询列表，可分页
    * @return array
    * @throws \think\Exception
    * @throws \think\db\exception\DataNotFoundException
    * @throws \think\db\exception\DbException
    * @throws \think\db\exception\ModelNotFoundException
    */
    public static function SelectBonusLedger_WebService($vipcode,$PageNo,$PageSize)
    {
        $StartTxDate = date("Ymd",strtotime("-3 month",time()));
        $EndTxDate = date("Ymd",strtotime(time()));
        $data0 = [
            'method' => 'SelectBonusLedger_WebService',
            'user' => 'TC',
            'crc' => '1505872460746',
            'sign' => 'e5532c2c6641367dfce34d025e51b784',
            'data' => [
                'VipCode' => $vipcode,
                'User' => 'YKT',
                'CircleId' => '',
                'StartTxDate' => $StartTxDate,
                'EndTxDate' => '',
                'Action' => '',
                'PageNo' => $PageNo, //分页功能：第几页
                'PageSize' => $PageSize, //分页功能：一页多少行
                'MallId' => '000001'
            ]
        ];
        $data2 = json_encode((object)$data0);
        $post_meta = self::crm_post_https($data2);
        $post_link = json_decode($post_meta);

        return $post_link;
    }
    /*
    * 科传积分调整
    * @return array
    * @throws \think\Exception
    * @throws \think\db\exception\DataNotFoundException
    * @throws \think\db\exception\DbException
    * @throws \think\db\exception\ModelNotFoundException
    */
    public static function BonusChange($vipcode,$jf,$body)
    {
        $data0 = [
            'method' => 'BonusChange_WebService',
            'user' => 'TC',
            'crc' => '1505872460746',
            'sign' => 'e5532c2c6641367dfce34d025e51b784',
            'data' => [
                'VipCode' => $vipcode,
                'User' => 'YKT',
                'Bonus' => $jf,
                'Action' => 'A',
                'Remark' => $body,
                'ReasonCode' => 'A',
                'MACAddress' => '01-01-6C-06-A6-20',
                'MallId' => '000001'
            ]
        ];
        $data2 = json_encode((object)$data0);
        $post_meta = self::crm_post_https($data2);
        $post_link = json_decode($post_meta);

        return $post_link;
    }
    /**
     * 科传CRM接口
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */


    /**
     * 科传ERP接口
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */


    /**
     * 科拓停车接口
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */

    /**
     * 生成订单号
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function makeNo($bid, $type)
    {
        $bid = $type . $bid;
        return $bid . strval(date('YmdHis') . mt_rand(1000000,9999999));
        // return $bid . strval(date('YmdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid('',true), 7, 13), 1))), 0, 5));
        //return $bid . strval(date('YmdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 4));
    }
}
